package main

import (
	"fmt"
	"github.com/volcengine/volc-sdk-golang/service/cdn"
	"os"
	"strconv"
	"time"
)

func main() {
	accessKey := os.Getenv("JIANMU_ACCESS_KEY")
	secretKey := os.Getenv("JIANMU_SECRET_KEY")
	certPath := os.Getenv("JIANMU_CERT_PATH")
	keyPath := os.Getenv("JIANMU_KEY_PATH")
	certDesc := os.Getenv("JIANMU_CERT_DESC")
	source := os.Getenv("JIANMU_SOURCE")

	execBind := os.Getenv("JIANMU_EXEC_BIND")
	bindDomain := os.Getenv("JIANMU_BIND_DOMAIN")

	if certDesc == "" {
		certDesc = fmt.Sprintf("upload_cert_%s", time.Now().Format("20060102_150405"))
	}

	if execBind == "" {
		execBind = "false"
	}

	// upload cert
	defaultInstance := cdn.DefaultInstance
	client := defaultInstance.Client
	client.SetAccessKey(accessKey)
	client.SetSecretKey(secretKey)

	certBytes, err := os.ReadFile(certPath)
	if err != nil {
		fmt.Println("无法读取证书文件:", err)
		os.Exit(1)
	}
	keyBytes, err := os.ReadFile(keyPath)
	if err != nil {
		fmt.Println("无法读取密钥文件:", err)
		return
	}

	aResp, err := defaultInstance.AddCdnCertificate(&cdn.AddCdnCertificateRequest{
		Certificate: cdn.Certificate{
			Certificate: cdn.GetStrPtr(string(certBytes)),
			PrivateKey:  cdn.GetStrPtr(string(keyBytes)),
		},
		CertInfo: &cdn.AddCdnCertInfo{
			Desc: cdn.GetStrPtr(certDesc),
		},
		Source: cdn.GetStrPtr(source),
	})
	if err != nil {
		fmt.Println("上传失败:", err)
		return
	}

	fmt.Println("%+v", aResp)

	// bind cert
	bind, _ := strconv.ParseBool(execBind)
	if bind {
		dResp, err := defaultInstance.BatchDeployCert(&cdn.BatchDeployCertRequest{
			CertId: aResp.Result,
			Domain: bindDomain,
		})
		if err != nil {
			fmt.Println("上传失败:", err)
			return
		}
		fmt.Println("%+v", dResp)
	}
}
